package org.example.rest.controller;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.example.user.ObjectFactory;
import org.example.user.User;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UserController {
	
	@RequestMapping(value="/post/", method=POST)
	@ResponseStatus(HttpStatus.CREATED)
	public ModelAndView post(@RequestBody User userRequest, HttpServletRequest request, HttpServletResponse response) {
		User userResponse = new ObjectFactory().createUser();
		response.addHeader("Location", determineLocationUri(request, "/user/" + userRequest.getId()));
		return new ModelAndView("user").addObject(userResponse);
	}

	@RequestMapping(value="/user/{id}", method=GET)
	@ResponseStatus(HttpStatus.CREATED)
	public ModelAndView get(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
		User userResponse = new ObjectFactory().createUser();
		userResponse.setId(Long.valueOf(id));
		return new ModelAndView("user").addObject(userResponse);
	}
	
	String determineLocationUri(HttpServletRequest request,	String newPathInfo) {
		StringBuffer url = request.getRequestURL();
		url.replace(url.indexOf(request.getPathInfo()), url.length(), newPathInfo);
		return url.toString();
	}	

}
